package com.liyu.iblog.dao.jpa;

import javax.persistence.EntityManager;
import javax.persistence.EntityTransaction;

import org.springframework.stereotype.Repository;

import com.liyu.iblog.dao.CategoryDao;
import com.liyu.iblog.domain.Blog;
import com.liyu.iblog.domain.Category;

@Repository("categoryDao")
public class CategoryDaoJpa extends GenericDaoJpa<Category> implements CategoryDao {

    public CategoryDaoJpa() {
        super(Category.class);
    }

    @Override
    public void updateCategoryForNewBlog(Blog blog) {
        EntityManager em = emf.createEntityManager();
        EntityTransaction tx = em.getTransaction();
        try {
            tx.begin();
            Category category = em.find(Category.class, blog.getCategoryKey());
            //if can not find the category create the new category
            if (category == null) {
                return;
            }
            category.getBlogKeys().add(blog.getKey());
            em.persist(category);
            tx.commit();
        } catch(Exception e) {
            e.printStackTrace();
        } finally {
            em.close();
        }
    }
    
    @Override
    public void updateCategoryForRemovedBlog(Object categoryKey, Object blogKey) {
        EntityManager em = emf.createEntityManager();
        EntityTransaction tx = em.getTransaction();
        try {
            tx.begin();
            Category category = em.find(Category.class, categoryKey);
            if (category != null) {
                category.getBlogKeys().remove(blogKey);
                em.persist(category);
            }
            tx.commit();
        } catch(Exception e) {
            e.printStackTrace();
        } finally {
            em.close();
        }
    }

}
